package cn.hftoday.web;

import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import cn.hftoday.db.*;
import cn.hftoday.core.*;

/**
 * Service interface
 * @author lane.cn@gmail.com
 *
 */
public class Front extends HttpServlet {
	static final long serialVersionUID = 3487516993124229998L;
	private static final Logger LOG = Logger.getLogger(Front.class);
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		throw new RuntimeException("error.wrong.method");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//set response charset and content type
		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		//load config file
		try {
			ApplicationConfig.getInstance().load();
		} 
		catch (Exception e) {
			LOG.fatal("error.app.config", e);
			cn.hftoday.core.Package errPackage = getFailPackage(0, e.getMessage());
			response.getOutputStream().println(errPackage.getXml());
			return;
		}

		//TODO get input package
		cn.hftoday.core.Package incomingPackage = new cn.hftoday.core.Package();
		String xml = new String(request.getParameter("xml").getBytes("ISO-8859-1"), "UTF-8");
		LOG.info("receive package: " + xml);

		//open database connections
		ConnectionPool.getInstance().open();
		try {
			//create conversation
			String sessionId = request.getSession(true).getId();
			Conversation conversation = 
				(Conversation)Mapper.getInstance().queryForObject("SelectConversationById", sessionId);
			if (conversation == null) {
				conversation = new Conversation();
				conversation.setCode(incomingPackage.getCode());
				conversation.setCreateTime(Calendar.getInstance());
				conversation.setId(sessionId);
				conversation.setRemember(false);
				conversation.setUpdateTime(Calendar.getInstance());
				Mapper.getInstance().insert("InsertConversation", conversation);
				LOG.info("create new conversation for session: " + sessionId);
			}
			else {
				conversation.setCode(incomingPackage.getCode());
				conversation.setUpdateTime(Calendar.getInstance());
				Mapper.getInstance().update("UpdateConversation", conversation);
				LOG.info("update existed conversation: " + sessionId);
			}
			
			//TODO process session and cookie
			
			//TODO process package
			//for debug: get return message
			cn.hftoday.core.Package outPackage = new cn.hftoday.core.Package();
			outPackage.setCode(incomingPackage.getCode());
			outPackage.setResult("ok");
			outPackage.setAttribute("incoming", xml);
			//debug end
	
			//feed back package to client side
			response.getWriter().println(outPackage.getXml());
		}
		catch (Exception e) {
			LOG.error("error.process.package", e);
			cn.hftoday.core.Package errPackage = getFailPackage(incomingPackage.getCode(), e.getMessage());
			response.getOutputStream().println(errPackage.getXml());
		}
		finally {
			ConnectionPool.getInstance().close();
		}
	}
	
	private cn.hftoday.core.Package getFailPackage(int code, String message) {
		cn.hftoday.core.Package p = new cn.hftoday.core.Package();
		p.setCode(code);
		p.setResult("ng");
		p.setMessage(message);
		return p;
	}
}
